/**
 * Created by xxx on 2017/3/27.
 */
var menuArray = [],serverUrl="..",isOnMenu = false;
localStorage.salesAuthority = "false";//销售是否有终端数据权限
var Menu = React.createClass({
    render: function () {
        return (
            <li className={this.props.data.parent?this.props.data.selectedClass+' parent '+this.props.data.parent:this.props.data.selectedClass } style={this.props.data.parent?{display:'none'}:{display:'block'}} onClick={this.props.omMenuClick} name={this.props.data.srcHref}>
                <div className="mainLeft-menu-li-div">
                    <img className="mainLeft-menu-li-img " src={this.props.data.imgSrc}/>
                    <span className="mainLeft-menu-li-text">{this.props.data.spanVal}<span className={this.props.data.spanVal=="线上购买"?"msgNumber msgNumber-buyOnline":"hidden"}/></span>
                </div>
                <span className={this.props.data.triangleClass}/>
            </li>
        );
    }
});
var MainPage = React.createClass({
    //定义组件初始状态
    getInitialState: function () {
        return {
            menuArray:this.props.menuArray,
            isOnlyPay:false,
            dataTerminal:false,
            menuOverflow: false,//菜单列表默认没有滚动条
            childMenuLength: 0,//二级菜单数量
        }
    },
    //第一次渲染的时候调用——ajax获取用户权限相关
    componentDidMount: function() {
        var svar = this;
        suixun.ajax(serverUrl+'/userManager/getMenu.json','',"get",function(data){
            if(data.code == 200){
                setTimeout(function () {
                    isOnMenu = false;
                },1500);
                var childMenuLength = 0;
                for(var i=0;i<data.info.length;i++){
                    var first = true;
                    var menu=data.info[i];
                    var url=menu.url;
                    if(url.indexOf(".json")>-1)
                        url=url.substring(0,url.length-5);
                    url+=".html";
                    if(menu.name == '线上购买'){
                        svar.setState({isOnlyPay:true});
                    }
                    if(i == 0){
                        menuArray.push({id:menu.id,parent:'',children:false,selectedClass:'mainLeft-menu-li checked',imgSrc:'../img/icon/'+menu.icon,triangleClass:'triangle show',spanVal:menu.name,srcHref:serverUrl+url});
                    }else{
                        menuArray.push({id:menu.id,parent:'',children:false,selectedClass:'mainLeft-menu-li',imgSrc:'../img/icon/'+menu.icon,triangleClass:'triangle hidden',spanVal:menu.name,srcHref:serverUrl+url});
                    }
                    if(menu.children.length>0){
                        for(var j = 0;j<menu.children.length;j++){
                            if(menu.children[j].icon){
                                var childUrl=menu.children[j].url;
                                if(childUrl.indexOf(".json")>-1)
                                    childUrl=childUrl.substring(0,childUrl.length-5);
                                childUrl+=".html";
                                //有功能菜单名称前缀
                                var spanVal = menu.children[j].name;
                                if(spanVal.indexOf('-')>0){
                                    spanVal = spanVal.split('-')[1]
                                }
                                menuArray.push({children:false,parent:'parent'+menu.id,selectedClass:'mainLeft-menu-li',imgSrc:'../img/icon/'+menu.children[j].icon,triangleClass:'triangle hidden',spanVal:spanVal,srcHref:serverUrl+childUrl});
                                if(first){
                                    menuArray[menuArray.length-2].children = true;
                                    first = false;
                                }
                                childMenuLength++;
                            }
                        }
                        // console.log(menuArray);
                    }
                    if(menu.name == "终端数据"){
                        svar.setState({dataTerminal:true});//没有设备管理权限不能再主页面搜索设备详情
                        localStorage.salesAuthority = "true";//销售是否有终端数据权限
                    }
                }
                svar.getMenuOverflow();
                //加载第一个菜单
                if(menuArray.length > 0){
                    $(".main-right-body-iframe").attr("src",menuArray[0].srcHref);
                }
                // console.log(menuArray);
                svar.setState({menuArray:menuArray,childMenuLength:childMenuLength});
                svar.getOtherInfo();
            }
        });
        //绑定回车时间
        $(document).keypress(function(e) {
            var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
            if (eCode == 13){
                if($(".enterEvent").is(":focus")){
                    svar.onMainLeftTopQuery();
                }
            }
        });
        $(window).resize(function (e) {
            svar.getMenuOverflow();
        });
    },
    //组件完成更新后立即调用
    getOtherInfo : function () {
        //查询当前登录的用户
        suixun.ajax(serverUrl+'/userManager/getUserName.json','',"get",function(data){
            if(data.code==200){
                localStorage.username = data.info;
                $(".username").html(data.info);
            }
        });
        if(this.state.isOnlyPay == false){
            return;
        }
        //查询线上购买
        suixun.ajax(serverUrl+'/onlinepayManage/getNotSendCounts.json','',"get",function(data){
            if(data.code==200 ){
                var orderNum = data.info.appNotSendCounts+data.info.chongqingNotSendCounts+data.info.discountNotSendCounts+data.info.newDiscountNotSendCounts;
                if(orderNum > 99){
                    $(".msgNumber-buyOnline").html("99+");
                }else if(0 < orderNum && orderNum <= 99){
                    $(".msgNumber-buyOnline").html(orderNum);
                }else{
                    $(".msgNumber-buyOnline").addClass(" hidden");
                }
            }else{
                $(".msgNumber-buyOnline").addClass(" hidden");
            }
        });
    },
    /**
     * 获取菜单的高度是否高于指定高度
     */
    getMenuOverflow: function () {
        var height = document.body.clientHeight,ulHeight = $(".mainLeft-menu-ol").height();//195
        var mum = this.state.menuArray.length-this.state.childMenuLength;
        if((height-mum*60)<195){
            this.setState({menuOverflow:true});
        }else{
            this.setState({menuOverflow:false});
        }
    },
    //修改密码
    chgPass: function (e) {
        var svar = this;
        var oldpass = $("#oldpass").val(),pass = $("#newpass").val(),newpass2 = $("#newpass2").val();
        if(oldpass == ''){
            suixun.alert("原密码不能为空!");
            $("#errorOldPass").show();
            return;
        }else if(oldpass.length < 6) {
            suixun.alert("原密码格式错误!");
            $("#errorOldPass").show();
            return;
        }else if(!/^[^\u4e00-\u9fa5]{0,}$/.test(oldpass)){
            suixun.alert("原密码格式错误!");
            $("#errorOldPass").show();
            return;
        }else{
            $("#errorOldPass").hide();
        }
        if(pass == ''){
            suixun.alert("新密码不能为空!");
            $("#errorNewpass").show();
            return;
        }else if(pass.length < 6) {
            suixun.alert("新密码格式错误!");
            $("#errorNewpass").show();
            return;
        }else if(!/^[^\u4e00-\u9fa5]{0,}$/.test(pass)){
            suixun.alert("新密码格式错误!");
            $("#errorNewpass").show();
            return;
        }else{
            $("#errorNewpass").hide();
        }
        if(newpass2 == ''){
            suixun.alert("确认新密码不能为空!");
            $("#errorNewpass2").show();
            return;
        }else if(newpass2.length < 6) {
            suixun.alert("确认新密码格式错误!");
            $("#errorNewpass2").show();
            return;
        }else if(!/^[^\u4e00-\u9fa5]{0,}$/.test(newpass2)){
            suixun.alert("确认新密码格式错误!");
            $("#errorNewpass2").show();
            return;
        }else{
            $("#errorNewpass2").hide();
        }
        if(pass != newpass2){
            suixun.alert("两次输入的新密码不一致");
            $("#newpass2").val("");
            return false;
        }
        var param="param={";
        param = getJsonDataNotEmpty(param,"workNumber",'"'+oldpass+'"');
        param = getJsonDataNotEmpty(param,"password",'"'+pass+'"');
        param += "}";
        suixun.ajax(serverUrl+'/userManager/changePassword.json',param,"get",function(data){
            if(data!=null && data.code == 200){
                suixun.alert("修改成功",function (data) {
                    if(data){
                        svar.onClickHidePop();
                    }
                });
            } else {
                suixun.alert((data!=null && data.msg!=null)?data.msg:"修改失败");
            }
        });
    },
    onClickHidePop: function () {
        $(".popPhone").hide();
    },
    //点击退出
    onClickShowPop: function () {
        $("#oldpass").val("");
        $("#newpass").val("");
        $("#newpass2").val("");
        $(".popPhone").show();
        return;
        var children = $(".mainLeft-menu-ol").children();
        for(var i = 0;i< children.length;i++){
            if($($(children[i])[0]).attr("name").indexOf("queryUser.html") > -1){
                $(".mainLeft-menu-li").eq($($(children[i])[0]).index()).addClass(" checked").siblings().removeClass(" checked");
                $(".mainLeft-menu-li > span").addClass(" hidden").removeClass(" show");
                $(".mainLeft-menu-li > span").eq($($(children[i])[0]).index()).addClass(" show").removeClass(" hidden");
                break;
            }
        }
        $(".main-right-body-iframe").attr("src",serverUrl+"/userManager/userInfo.html");
    },
    /**
     * 根据IMEI、phone查询
     */
    onMainLeftTopQuery: function () {
        var inputVal = $(".queryVal").val();
        if(inputVal == ""){
            suixun.alert("输入框的值不能为空!");
            return;
        }else if(/^[^\u4e00-\u9fa5]{0,}$/.test(inputVal)){
            if($(".current-display").html() == "设备IMEI号" && inputVal.length != 14){
                suixun.alert("输入框的值格式错误!");
                return;
            }else if($(".current-display").html() == "设备IMEI号" && inputVal.length == 14){
                localStorage.mdtid= $(".queryVal").val();
                localStorage.deviceType = "mdtid";
            }else if(($(".current-display").html() == "设备手机号"||$(".current-display").html() == "家长手机号") && inputVal.length != 11){
                suixun.alert("输入框的值格式错误!");
                return;
            }else if($(".current-display").html() == "设备手机号" && inputVal.length == 11){
                localStorage.deviceType = "simid";
                localStorage.simid= $(".queryVal").val();
            }
            this.changeMenuSelected('queryDeviceList.html');
            // var children = $(".mainLeft-menu-ol").children();
            // for(var i = 0;i< children.length;i++){
            //     if($($(children[i])[0]).attr("name").indexOf("queryDeviceList.html") > -1){
            //         $(".mainLeft-menu-li").eq($($(children[i])[0]).index()).addClass(" checked").siblings().removeClass(" checked");
            //         $(".mainLeft-menu-li > span").addClass(" hidden").removeClass(" show");
            //         $(".mainLeft-menu-li > span").eq($($(children[i])[0]).index()).addClass(" show").removeClass(" hidden");
            //         break;
            //     }
            // }
            if($(".current-display").html() == "家长手机号" && inputVal.length == 11){
                $(".main-right-body-iframe").attr("src",serverUrl+"/deviceManage/parentDeviceList.html?parentPhone="+inputVal);
            }else{
                $(".main-right-body-iframe").attr("src",serverUrl+"/deviceManage/deviceInfo.html");
            }
        }else{
            suixun.alert("输入框的值格式错误!",function (data) {
                if(data){
                    $(".queryVal").val("");
                }
            });
        }

    },
    /**
     * 点击菜单 页面底部有跳转的
     * @param data
     */
    omMenuClick: function (data,e) {
        if (isOnMenu == false) {
            this.changeMenuSelected(data.srcHref);
            if(data.children) {
                isOnMenu = false;
                if($(".parent" + data.id + "").is(":hidden")) {
                    $(".parent" + data.id + "").show();
                    $(".menuOverflow").scrollTop($('.menuOverflow').scrollTop()+36);//2017年12月4日11:47:10 叙刚提出的优化
                    $(".updown"+data.id).addClass(' down');
                }else{
                    $(".parent" + data.id + "").hide();
                    $(".updown"+data.id).removeClass(' down');
                }
            }else{
                isOnMenu = true;
                setTimeout(function () {
                    isOnMenu = false;
                }, 800);//1500
                $(".main-right-body-iframe").attr("src", data.srcHref);
            }
        }
    },
    /**
     * 设置左侧菜单选中
     */
    changeMenuSelected: function (src) {
        var menuArray = this.state.menuArray,index = 0;
        for(var k = 0;k<menuArray.length;k++){
            if(menuArray[k].srcHref.indexOf(src)>-1){
                menuArray[k].selectedClass = 'mainLeft-menu-li checked';
                menuArray[k].triangleClass = 'triangle show';
                index = k*60;
                //如果是子节点——让父节点显示出来
                if(menuArray[k].parent){
                    var id = menuArray[k].parent.substring(6,menuArray[k].parent.length);//获取父节点id
                    $(".parent" + id + "").show();
                    $(".updown"+ id).addClass(' down');
                }
            }else{
                menuArray[k].selectedClass='mainLeft-menu-li ';
                menuArray[k].triangleClass = 'triangle hidden';
            }
        }
        this.setState({menuArray:menuArray});
        setTimeout(function () {
            // $(".menuOverflow").scrollTop(index);//设置滚动条
        },20);
    },
    //点击退出
    onQuit: function () {
        suixun.confirm_noTit('是否退出系统?',function (data) {
            if(data == true) {
                suixun.ajax(serverUrl + '/userManager/logout.json','',"get",function(data){
                    window.location.href = "../login/login.html";
                });
            }
        });
    },
    //验证
    onBlurInput: function (e) {
        var classname = e.target.getAttribute("data-error"),dataPlac = $(e.target).attr("data-plac"),inputVal = $(e.target).val();
        if(inputVal == ''){
            suixun.alert(dataPlac+"不能为空!");
            $("."+classname+"").show();
        }else if(inputVal.length < 6) {
            suixun.alert(dataPlac+"格式错误!");
            $("."+classname+"").show();
        }else if(!/^[^\u4e00-\u9fa5]{0,}$/.test(inputVal)){
            suixun.alert(dataPlac+"格式错误!");
            $("."+classname+"").show();
        }else{
            $("."+classname+"").hide();
        }
    },
    /**
     * iframe 地址重新加载后的
     */
    changeIframeUrl:function (e) {
        var url = e.target.contentWindow.location.href;
        url = url.split('/')[url.split('/').length-1];
        // console.log(url+'-----------------------------------------------')
        //终端数据
        if(url == 'deviceInfo.html' || url == 'deviceOperationHistory.html' || url.indexOf('parentDeviceList.html')>-1 || url == 'deviceOperationHistory.html'){
            url = 'queryDeviceList.html';
        }
        //初始化
        if(url == 'queryDeviceInitList.html' || url == 'querySimInfoList.html' || url == 'queryonReserveList.html' || url == 'attendanceMange.html' || url == 'queryonReserveListDetail.html'){
            url = 'querySchoolList.html';
        }
        //实时监控
        if(url == 'queryMonitorListDetail.html' ){
            url = 'queryMonitorList.html';
        }
        //信息管理
        if(url == 'classTeacher.html' || url == 'queryStduentList.html'){
            url = 'queryParentList.html';
        }
        //商户中心-地区配卷
        if(url == 'addInformation.html' ){
            url = 'addressTicket.html';
        }
        //价格管理
        if(url == 'schoolPrice.html' || url == 'devicePrice.html'){
            url = 'getSystemPrice.html';
        }
        setTimeout(function () {
            this.changeMenuSelected(url);
        }.bind(this),200);

    },
    render: function () {
        {
            var svar = this;
            // var onMenuArray = [this.omMenuClick];
            var Menus = this.state.menuArray.map(function (data) {
                return (
                    <li className={data.parent?data.selectedClass+' parent '+data.parent:data.selectedClass } style={data.parent?{display:'none'}:{display:'block'}} onClick={this.omMenuClick.bind(svar,data)} name={data.srcHref}>
                        <div className="mainLeft-menu-li-div">
                            <img className="mainLeft-menu-li-img " src={data.imgSrc}/>
                            <span className="mainLeft-menu-li-text">
                                {data.spanVal}
                                <span className={data.spanVal=="线上购买"?"msgNumber msgNumber-buyOnline":"hidden"}/>
                                {
                                    data.children?<span className={"menu-haveChild updown"+data.id}></span>:''
                                }
                            </span>
                        </div>
                        <span className={data.triangleClass}/>
                    </li>
                    // <Menu key={data.spanVal} data={data} omMenuClick={onMenuArray[0].bind(svar,data)} />
                )
            }.bind(this));
        }
        return (
            <div className="MainPage">
                <div className="main-left">
                    <div id="mainLeft">
                        <div className="mainLeft-top">
                        </div>
                        <div className="mainLeft-body">
                            <div className="mainLeft-header">
                                <div className="mainLeft-header-text">
                                    我的菜单
                                </div>
                                <div className="mainLeft-header-img ">
                                </div>
                            </div>
                            <div className="mainLeft-menu" id="mainLeft-menu">
                                <div style={{width:"100%",height:"12px"}}></div>
                                <ol style={{background:'#2f323b'}} className={this.state.menuOverflow?"mainLeft-menu-ol menuOverflow":"mainLeft-menu-ol"}>
                                    {Menus}
                                </ol>
                                <div className="Con_Scorll" id="Con_Scorll">
                                    <div className="Do_Scorll" id="Do_Scorll" ></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div className="main-right">
                    <div className="main-right-top">
                        <div id="mainRightTop">
                            <div className="mainRightTop-left" style={svar.state.dataTerminal == true?{display:'block'}:{display:'none'}}>
                                <div className="mainRightTop-left-select droup-select">
                                    <div className="current-display">设备IMEI号</div>
                                    <span className="lower-right-corner"/>
                                    <div className="drop-down" >
                                        <span className="equipment-number equipment-imei" >设备IMEI号</span>
                                        <span className="equipment-number equipment-imei" >设备手机号</span>
                                        <span className="equipment-number equipment-phone" >家长手机号</span>
                                    </div>
                                </div>
                                <div className="mainRightTop-left-query">
                                    <div className="mainRightTop-left-query-input">
                                        <input className="queryVal enterEvent" type="text" placeholder="输入设备IMEI号" maxLength="14"/>
                                    </div>
                                    <div className="mainRightTop-left-query-img" onClick={this.onMainLeftTopQuery}></div>
                                </div>
                            </div>
                            :''

                            <div className="mainRightTop-right">
                                <div className="mainRightTop-right-user" style={{cursor:"pointer"}}  onClick={this.onClickShowPop} >
                                    <img className="userimg" src="../img/icon/userDefaultImg.png"/>
                                    <span className="username" />
                                </div>
                                <div className="mainRightTop-right-quit" onClick={this.onQuit}>
                                    <img src="../img/icon/quit.png"/>
                                    <span>退出登录</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="main-right-body">
                        <iframe frameborder="no" id="mainIframe" className="main-right-body-iframe" src="javsscript:void(0)" onLoad={this.changeIframeUrl.bind(this)}></iframe>
                    </div>
                </div>
                <form name="passForm">
                    <div className="popPhone popModel">
                        <input type="hidden" name="id" id="id" value=""/>
                        <div className="model"></div>
                        <div className="popPhone-info popUser-info popModel-info">
                            <div className="popModel-title">
                                        <span className="popModel-title-content">
                                            <span className="popModel-title-content-solid-left" />
                                            <span className="table-form-title">修改登录密码</span>
                                            <span className="popModel-title-content-solid-right" />
                                        </span>
                                <span className="popModel-title-img" onClick={this.onClickHidePop}><img src="../img/icon/close.png" alt="关闭"/></span>
                            </div>
                            <div className="popModel-body">
                                <div className="popModel-body-input">
                                    <span className="popModel-body-input-title">原密码</span>
                                    <span className="popModel-body-input-content">
                                        <input className="input-content" type="password" name="oldpass" id="oldpass" data-plac="原密码" placeholder="请输入原密码" data-error="oldpass-error" maxLength="20" onBlur={this.onBlurInput}  />
                                    </span>
                                    <div id="errorOldPass" className="errorMsg oldpass-error" ></div>
                                </div>
                                <div className="popModel-body-input">
                                    <span className="popModel-body-input-title">新密码</span>
                                    <span className="popModel-body-input-content">
                                        <input className="input-content" type="password" name="newpass" id="newpass" data-plac="新密码" placeholder="请输入6~20数字和字母组成的新密码" data-error="newpass-error" maxLength="20"  onBlur={this.onBlurInput}  />
                                    </span>
                                    <div id="errorNewpass" className="errorMsg newpass-error" ></div>
                                </div>
                                <div className="popModel-body-input">
                                    <span className="popModel-body-input-title nextPossword">确认新密码</span>
                                    <span className="popModel-body-input-content">
                                        <input className="input-content" type="password" name="newpass2" id="newpass2" data-plac="确认新密码" placeholder="请再次输入6~20数字和字母组成的新密码" data-error="newpass2-error" maxLength="20"  onBlur={this.onBlurInput}  />
                                    </span>
                                    <div id="errorNewpass2" className="errorMsg newpass2-error" ></div>
                                </div>
                            </div>
                            <div className="popModel-button">
                                <span className="popModel-button-ok" onClick={this.chgPass}>确定</span>
                            </div>
                        </div>
                    </div>
                </form>

            </div>
        )
    }
});
ReactDOM.render(
    <MainPage menuArray={menuArray}/>,
    document.getElementById('main')
);
//点击左侧menu
// $(".mainLeft-menu").on('click','.mainLeft-menu-li',function () {
//     if(isOnMenu == false){
//         $(".mainLeft-menu-li").eq($(this).index()).addClass(" checked").siblings().removeClass(" checked");
//         $(".mainLeft-menu-li > span").addClass(" hidden").removeClass(" show");
//         $(".mainLeft-menu-li > span").eq($(this).index()).addClass(" show").removeClass(" hidden");
//     }
// });
var mainLeft = false;
//收缩、展开左侧
$(".mainLeft-header-img").click(function () {
    console.log(mainLeft);
    if(mainLeft){
        $(".main-left").animate({width:'180px'},300,function () {
            $(".mainLeft-header-img").removeClass(" mainLeft-header-img-shrink");
            $(".mainLeft-top").removeClass("mainLeft-top-shrink");
            $(".mainLeft-menu-ol").removeClass("mainLeft-top-shrink");
            $(".mainLeft-menu-li-div").removeClass(" mainLeft-menu-li-div-shrink");
            $(".mainLeft-menu-li-text,.mainLeft-header-text").show();
        });
        $(".main-right").animate({marginLeft:'180px'},300);
        mainLeft = false;
    }else{
        $(".main-left").animate({width:'80px'},300);
        $(".main-right").animate({marginLeft:'80px'},300);
        $(".mainLeft-header-img").addClass(" mainLeft-header-img-shrink");
        $(".mainLeft-top").addClass("mainLeft-top-shrink");
        $(".mainLeft-menu-ol").addClass("mainLeft-top-shrink");
        $(".mainLeft-menu-li-text,.mainLeft-header-text").hide();
        $(".mainLeft-menu-li-div").addClass(" mainLeft-menu-li-div-shrink");
        mainLeft = true;
    }
});
//点击下拉框
$("*").bind("click",function(e){
    var target = $(e.target);
    if(target.closest(".mainRightTop-left-select").length == 1){
    }else if(target.closest(".mainLeft-menu-li").length == 1){//添加这个是因为当子页面有下拉列表展开的时候切换菜单“$("#mainIframe").contents().find(".drop-down").slideUp();”会报错
        $('.drop-down').slideUp();
    }else{
        $('.drop-down').slideUp();
        $("#mainIframe").contents().find(".drop-down").slideUp();
    }
});
$(".mainRightTop-left-select").click(function () {
    $('.drop-down',$(".main-right-body-iframe")).slideUp();
    var dropDown = $(this).find('.drop-down');
    if(dropDown.is(":hidden")){
        dropDown.slideDown();
    }else{
        dropDown.slideUp();
    }
});
//选择IMEI、phone
$('.drop-down>span').click(function() {
    $(".queryVal").attr("placeholder","输入"+$(this).html());
    if($(this).html() == "设备手机号" && $(".current-display").html() != "设备手机号" || $(this).html() == "家长手机号" && $(".current-display").html() != "家长手机号" ){
        $(".queryVal").attr("maxLength","11");
        $(".enterEvent").val("");
    }else if($(this).html() == "设备IMEI号" && $(".current-display").html() != "设备IMEI号"){
        $(".queryVal").attr("maxLength","14");
        $(".enterEvent").val("");
    }
    $(".current-display").html($(this).html());
    $('.drop-down').slideUp();
});
$(".popPhone").hide();